<template>
    <div class="app-container">
      <el-card v-if="dialogHistory.length > 0" shadow="hover" class="response-card">
        <div v-for="(message, index) in dialogHistory" :key="index" class="message">
          <div class="message-box" :class="{'user-message': message.role === 'user', 'bot-message': message.role === 'bot'}">
            <p class="message-text" v-if="message.role === 'user'">
              {{ message.content }}
            </p>
            <p class="message-text" v-else>
              {{ message.content }}
            </p>
            <div class="avatar-container" :class="{ right: message.role === 'user', left: message.role === 'bot' }">
              <img :src="message.role === 'user' ? userAvatar : botAvatar" alt="Avatar" class="avatar">
              <span class="timestamp">{{ message.timestamp }}</span>
            </div>
          </div>
        </div>
      </el-card>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" class="input-form">
        <el-form-item label="输入内容" prop="content">
          <el-input
            v-model="queryParams.content"
            placeholder="请输入您的问题"
            clearable
            @keyup.enter.native="handleSend"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSend">发送</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" icon="el-icon-refresh" size="mini" @click="clearMessages">清屏</el-button>
        </el-form-item>
      </el-form>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  import moment from 'moment';
  
  export default {
    name: 'AppChat',
    data() {
      return {
        queryParams: {
          content: ''
        },
        dialogHistory: [],
        showSearch: true,
        loading: false,
        userAvatar: 'https://cpanda.oss-cn-beijing.aliyuncs.com/profile.png',
        botAvatar: 'https://cpanda.oss-cn-beijing.aliyuncs.com/lyydw.png'
      };
    },
    methods: {
      async handleSend() {
        if (!this.queryParams.content.trim()) {
          alert('请输入内容');
          return;
        }
  
        this.loading = true;
  
        // 获取当前时间
        const timestamp = moment().format('YYYY-MM-DD HH:mm:ss');
  
        // 将用户的消息添加到对话历史中
        this.dialogHistory.push({
          role: 'user',
          content: this.queryParams.content,
          timestamp: timestamp
        });
  
        try {
          const response = await axios.post('http://localhost:9090/web/chat/ai', this.queryParams.content, {
            headers: {
              'Content-Type': 'application/json'
            }
          });
  
          const botResponse = response.data;
  
          // 将机器人的响应添加到对话历史中
          this.dialogHistory.push({
            role: 'bot',
            content: botResponse,
            timestamp: timestamp
          });
  
          this.queryParams.content = ''; // 清空输入框
        } catch (error) {
          console.error('Error:', error);
          this.dialogHistory.push({
            role: 'bot',
            content: '请求失败，请稍后重试',
            timestamp: timestamp
          });
        } finally {
          this.loading = false;
        }
      },
      clearMessages() {
        this.dialogHistory = [];
      },
      // 实现逐字渲染效果
      renderText(text, element) {
        let index = 0;
        const interval = setInterval(() => {
          if (index < text.length) {
            element.textContent += text.charAt(index);
            index++;
          } else {
            clearInterval(interval);
          }
        }, 50); // 调整渲染速度
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.dialogHistory.forEach(message => {
          const element = document.querySelector(`.message-text.${message.role}`);
          if (element) {
            this.renderText(message.content, element);
          }
        });
      });
    }
  };
  </script>
  
  <style scoped>
  .app-container {
    max-width: 600px;
    margin: 0 auto;
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    height: 100vh;
  }
  
  .response-card {
    flex-grow: 1;
    margin-bottom: 10px;
    padding: 20px;
    background-color: #f9fafb;
    border-radius: 4px;
    overflow-y: scroll;
    height: 70vh; /* 增加高度 */
  }
  
  .message {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .message-box {
    flex-grow: 1;
    background-color: #ffffff;
    padding: 10px;
    border-radius: 4px;
    position: relative;
    white-space: pre-wrap; /* 使文本自动换行 */
    word-break: break-word; /* 在单词中间断行 */
    margin-top: 30px;
  }
  
  .avatar-container {
    position: absolute;
    top: -35px;
    display: flex;
    align-items: center;
  }
  
  .avatar-container.right {
    right: 10px;
  }
  
  .avatar-container.left {
    left: 10px;
  }
  
  .avatar {
    width: 30px;
    height: 30px;
    border-radius: 50%;
  }
  
  .timestamp {
    margin-left: 5px;
    font-size: 12px;
    color: #666;
  }
  
  .message-text {
    display: inline-block;
  }
  
  .user-message {
    background-color: #f0f0f0;
    margin-left: 0;
    margin-right: 40px;
  }
  
  .bot-message {
    background-color: #e0f0ff;
    margin-left: 40px;
    margin-right: 0;
  }
  
  .input-form {
    margin-top: 10px;
    width: 100%; /* 输入框单独一行 */
  }
  
  .el-input {
    width: 100%; /* 输入框占满宽度 */
  }
  
  .el-button {
    margin-left: 10px;
  }
  </style>
  